import { login, getUserInfo, getUserById } from '@/api/user'
import { getToken, setToken, setTimeStamp, removeToken } from '@/utils/auth'
const state = {
  token: getToken(),
  userInfo: {}
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
    setTimeStamp()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  },
  removeToken(state) {
    state.token = null
    removeToken()
  }
}

const actions = {
  async login({ commit }, data) {
    const token = await login(data)
    commit('setToken', token)
  },
  logout({ commit }) {
    commit('removeUserInfo')
    commit('removeToken')
  },
  async getUserInfo({ commit }) {
    const userInfo = await getUserInfo()
    const { staffPhoto: photo } = await getUserById(userInfo.userId)
    commit('setUserInfo', {
      ...userInfo,
      photo
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
